package com.heima.freemarker.test;

import com.heima.freemarker.FreemarkerApp;
import com.heima.freemarker.entity.Student;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest(classes = FreemarkerApp.class)
@RunWith(SpringRunner.class)
public class FreemarkerTest2 {
    @Autowired
    private Configuration configuration;

    @Test
    public void test() throws Exception {
        //通过模板文件,创建模板对象
        Template template = configuration.getTemplate("list.ftl");

        Map<String, Object> data = getData();
        /**
         * 合成
         * 第一个参数:模型数据,就是数据
         * 第二个参数:合成后的输出流
         */

        template.process(data, new FileWriter("d:/list.html"));


    }

    private Map<String, Object> getData() {
        HashMap<String, Object> map = new HashMap<>();

        //小强对象模型数据
        Student stu1 = new Student();
        stu1.setName("小强");
        stu1.setAge(18);
        stu1.setMoney(1999.88f);

        Student stu2 = new Student();
        stu2.setName("小红");
        stu2.setAge(22);
        stu2.setMoney(666.6f);

        List<Student> list = new ArrayList<>();
        list.add(stu1);
        list.add(stu2);

        map.put("list",list);

        HashMap<String, Student> stuMap = new HashMap<>();
        stuMap.put("stu1",stu1);
        stuMap.put("stu2",stu2);

        map.put("stuMap",stuMap);
        return map;
    }


}
